package com.xbjtech.service.impl;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.xbjtech.mapper.UserMapper;
import com.xbjtech.model.User;
import com.xbjtech.model.UserExample;
import com.xbjtech.model.UserExample.Criteria;
import com.xbjtech.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	UserMapper userMapper;
	
	@Override
	public User selectUserByUsername(String username) {
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<User> users = userMapper.selectByExample(example);
		if (null != users && !users.isEmpty()) {
			return users.get(0);
		}
		return null;
	}

	@Override
	public User selectUserByMobile(String mobile) {
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andMobileEqualTo(mobile);
		List<User> users = userMapper.selectByExample(example);
		if (null != users && !users.isEmpty()) {
			return users.get(0);
		}
		return null;
	}

	@Override
	public List<User> listUsers(UserExample example, Integer page, Integer rows) {
		PageHelper.startPage(page, rows);
		return userMapper.selectByExample(example);
	}

	@Override
	public void insertUser(User user) {
		user.setLocked(0);
		user.setDeleted(0);
		userMapper.insert(user);
		user.setPassword(DigestUtils.md5Hex(user.getId()+user.getPassword()));
		userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public void updateUser(User user) {
		userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public void deleteUserById(Long id) {
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(id);
		User user = new User();
		user.setDeleted(1);
		userMapper.updateByExampleSelective(user, example);
	}

}
